# 导入tushare
import tushare as ts
# 初始化pro接口
pro = ts.pro_api('47b4cad5b8693e659ce45d1625d20211311ccb4039d69ba828736eb4')

# 拉取数据
df = pro.daily(**{
    "ts_code": "",
    "trade_date": "",
    "start_date": 20250310,
    "end_date": 20250330,
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])
print(df)


# 导入tushare
import tushare as ts
# 初始化pro接口
pro = ts.pro_api('1c7f85b9026518588c0d0cdac712c2d17344332c9c8cfe6bc83ee75c')

# 拉取数据
df1 = pro.stock_basic(**{
    "ts_code": "",
    "name": "",
    "exchange": "",
    "market": "",
    "is_hs": "",
    "list_status": "",
    "limit": "",
    "offset": ""
}, fields=[
    "ts_code",
    "symbol",
    "name",
    "area",
    "industry",
    "cnspell",
    "market",
    "list_date",
    "act_name",
    "act_ent_type"
])
print(df1)


import pandas as pd
import tushare as ts
from datetime import datetime, timedelta

# 初始化pro接口
pro = ts.pro_api('47b4cad5b8693e659ce45d1625d20211311ccb4039d69ba828736eb4')

# 获取上一个交易日日期
today = datetime.now()
last_trade_date = (today - timedelta(days=1)).strftime('%Y%m%d')  # 简单处理，实际应查询交易日历

# 拉取上一个交易日的数据
df_daily = pro.daily(trade_date=last_trade_date)

# 显示数据前几行和基本信息
print("数据前几行:")
print(df_daily.head())
print("\n数据基本信息:")
print(df_daily.info())

# 生成统计表
stats = df_daily.describe()
print("\n数据统计表:")
print(stats)

# 更详细的分析
print("\n=== 更详细的数据分析 ===")

# 1. 缺失值检查
print("\n缺失值统计:")
print(df_daily.isnull().sum())

# 2. 涨跌幅分布
print("\n涨跌幅分布情况:")
print(df_daily['pct_chg'].describe())

# 3. 成交量与涨跌幅的关系
high_volume = df_daily[df_daily['vol'] > df_daily['vol'].quantile(0.9)]
print("\n高成交量股票的涨跌幅统计:")
print(high_volume['pct_chg'].describe())

# 4. 价格变动分析
df_daily['price_change'] = df_daily['close'] - df_daily['open']
print("\n价格变动(收盘-开盘)统计:")
print(df_daily['price_change'].describe())



import pandas as pd
import numpy as np

# 假设df_daily是您获取的日线数据
# 按股票代码和交易日期排序，为计算技术指标做准备
df_daily = df_daily.sort_values(['ts_code', 'trade_date'])

# 转换日期格式
df_daily['trade_date'] = pd.to_datetime(df_daily['trade_date'], format='%Y%m%d')

# 检查缺失值
print("缺失值统计:")
print(df_daily.isnull().sum())

# 如果有缺失值，可以向前填充或删除
# df_daily = df_daily.fillna(method='ffill')
# 或者删除缺失值
# df_daily = df_daily.dropna()

# 确保数据按股票代码和时间排序
df_daily = df_daily.sort_values(['ts_code', 'trade_date'])

# 计算MA5和MA10
def calculate_moving_averages(df):
    df['ma5'] = df['close'].rolling(window=5, min_periods=1).mean()
    df['ma10'] = df['close'].rolling(window=10, min_periods=1).mean()
    return df
# 按股票代码分组计算
df_with_ma = df_daily.groupby('ts_code').apply(calculate_moving_averages)

# 查看结果
print(df_with_ma[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']].tail())

import pandas as pd
import tushare as ts
from datetime import datetime, timedelta

# 初始化Tushare Pro接口
pro = ts.pro_api('您的Tushare Token')


def get_stock_data():
    """获取股票日线数据并计算均线"""
    # 获取上一个交易日日期
    today = datetime.now()
    last_trade_date = (today - timedelta(days=1)).strftime('%Y%m%d')

    # 拉取日线数据
    df_daily = pro.daily(trade_date=last_trade_date)

    # 获取股票基本信息
    df_basic = pro.stock_basic(exchange='', list_status='L')

    # 合并数据
    df = pd.merge(df_daily, df_basic[['ts_code', 'name']], on='ts_code', how='left')

    # 按股票代码和日期排序
    df = df.sort_values(['ts_code', 'trade_date'])

    # 计算MA5和MA10
    def calculate_ma(data):
        data['ma5'] = data['close'].rolling(window=5).mean()
        data['ma10'] = data['close'].rolling(window=10).mean()
        return data

    df = df.groupby('ts_code').apply(calculate_ma)

    return df


def identify_cross_points(df):
    """识别MA5上穿MA10的股票"""
    # 计算交叉信号
    df['ma5_above_ma10'] = df['ma5'] > df['ma10']
    df['cross_signal'] = df['ma5_above_ma10'] & (~df['ma5_above_ma10'].shift(1).fillna(False))

    # 筛选出发生交叉的股票
    cross_stocks = df[df['cross_signal']].copy()

    # 添加交叉点价格信息
    cross_stocks['cross_price'] = cross_stocks['close']

    return cross_stocks[['ts_code', 'name', 'trade_date', 'close', 'ma5', 'ma10', 'cross_price']]


def calculate_rsi(data, period=14):
    # 计算每日涨跌幅
    delta = data['close'].diff()
    up = delta.clip(lower=0)
    down = -delta.clip(upper=0)

    # 计算平均上涨和下跌幅度
    avg_up = up.rolling(window=period).mean()
    avg_down = down.rolling(window=period).mean()

    # 计算相对强弱指数
    rs = avg_up / avg_down
    rsi = 100 - (100 / (1 + rs))
    return rsi

# 确保数据按日期排序
df = df.sort_values(by='trade_date')

# 计算RSI
df['rsi'] = calculate_rsi(df)

print(df)

import tushare as ts
import pandas as pd

# 初始化pro接口
pro = ts.pro_api('47b4cad5b8693e659ce45d1625d20211311ccb4039d69ba828736eb4')

# 拉取数据，扩大时间范围
start_date = '20250101'
end_date = '20250330'
df = pro.daily(**{
    "ts_code": "",
    "trade_date": "",
    "start_date": start_date,
    "end_date": end_date,
    "offset": "",
    "limit": ""
}, fields=[
    "ts_code",
    "trade_date",
    "open",
    "high",
    "low",
    "close",
    "pre_close",
    "change",
    "pct_chg",
    "vol",
    "amount"
])

# 按股票代码分组
grouped = df.groupby('ts_code')

buy_point_stocks = []

for ts_code, group in grouped:
    # 按日期排序
    group = group.sort_values(by='trade_date')

    # 去除缺失值
    group = group.dropna(subset=['close'])

    # 确保数据量足够计算10日移动平均线
    if len(group) < 10:
        continue

    # 计算5日和10日移动平均线
    group['ma_5'] = group['close'].rolling(window=5).mean()
    group['ma_10'] = group['close'].rolling(window=10).mean()

    # 从第10天开始判断
    for i in range(9, len(group)):
        prev_ma_5 = group['ma_5'].iloc[i - 1]
        prev_ma_10 = group['ma_10'].iloc[i - 1]
        current_ma_5 = group['ma_5'].iloc[i]
        current_ma_10 = group['ma_10'].iloc[i]

        # 判断是否5日线上穿10日线
        if prev_ma_5 < prev_ma_10 and current_ma_5 > current_ma_10:
            buy_point_stocks.append(group.iloc[i])
            break

# 转换为DataFrame
buy_point_df = pd.DataFrame(buy_point_stocks)

print(buy_point_df)
# 确保数据按股票代码和交易日期排序
df = df.sort_values(by=['ts_code', 'trade_date'])

# 计算MA5和MA10
df['ma5'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=5).mean())
df['ma10'] = df.groupby('ts_code')['close'].transform(lambda x: x.rolling(window=10).mean())

# 打印前20行以检查MA计算
print(df[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']].head(20))

# 找出5日线上穿10日线的时刻
df['ma5_cross_ma10'] = (df['ma5'] > df['ma10']) & (df['ma5'].shift(1) <= df['ma10'].shift(1))

# 打印交叉条件检查
df['ma5_greater_than_ma10'] = df['ma5'] > df['ma10']
df['ma5_prev_less_than_ma10'] = df['ma5'].shift(1) <= df['ma10'].shift(1)
print(df[['ts_code', 'trade_date', 'ma5', 'ma10', 'ma5_greater_than_ma10', 'ma5_prev_less_than_ma10']].head(20))

# 提取出买点股票
buy_signals = df[df['ma5_cross_ma10']]

# 获取股票列表
buy_stock_list = buy_signals[['ts_code', 'trade_date']].drop_duplicates().sort_values(by=['ts_code', 'trade_date'])

# 打印买点股票列表
print(buy_stock_list)

# 将结果保存到CSV文件
buy_stock_list.to_csv('buy_signals.csv', index=False)